#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <string>

const int size =4096;
const int projid = 0x66;
const int gmode = 0666;
const std::string pathname = ".";
int main()
{
    int shmid;
    void *start_mem;

                                                                          
    key_t key = ftok(pathname.c_str(), projid);
    if (key < 0)
    {
        perror("ftok");
        exit(1);
    }
    printf("key: 0x%x\n", key);

    shmid = shmget(key, size, IPC_CREAT | IPC_EXCL | gmode);
    if (shmid < 0)
    {
        perror("shmget");
        exit(1);
    }
    printf("shmid: %d\n", shmid);

    start_mem = static_cast<char *>(shmat(shmid, nullptr, 0));
    if ((long long)start_mem < 0)
    {
        perror("shmat");
        exit(1);
    }
    printf("attach success\n");
    
    strncpy((char *)start_mem, "i am process A", size);

    if (shmdt(start_mem) < 0)
    {
        perror("shmdt");
        exit(1);
    }
    printf("detach success\n");

    printf("Process A has written the message.\n");

    return 0;
}